package com.yexiao.cofe.util;

import cn.hutool.core.util.StrUtil;
import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.yexiao.cofe.business.pojo.User;
import com.yexiao.cofe.common.exception.BusinessException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

public class JwtUtil {

    private static final Logger logger = LoggerFactory.getLogger(JwtUtil.class);

    /**
     * 密钥
     */
    private static final String SECRET = "661d1a110fb54c02b477a3b830cfbf0a";

    /**
     * 过期时间,单位：秒
     */
    private static final long Default_Expire_Time = 1800L;

    /**
     * 生成token
     */
    public static String createToken(User user) {
        // 过期时间
        Date expireDate = new Date(System.currentTimeMillis() + Default_Expire_Time * 1000L);

        Map<String, Object> header = new HashMap<>();
        header.put("alg", "HS256"); // 加密算法 HMAC SHA256
        header.put("typ", "JWT"); // 类型

        return JWT.create().withHeader(header)
                .withClaim("userId", user.getUserId())
                .withClaim("userName", user.getUserName())
                .withClaim("phone", user.getPhone())
                .withExpiresAt(expireDate)
                .withIssuedAt(new Date())
                .sign(Algorithm.HMAC256(SECRET));
    }

    /**
     * 解析token
     */
    public static Map<String, Object> verityToken(String token) {
        Map<String, Object> map = new HashMap<>();
        if(StrUtil.isEmpty(token)) {
            throw new BusinessException("token为空");
        }

        DecodedJWT decodedJWT = JWT.decode(token);
        Map<String, Claim> claims = decodedJWT.getClaims();
        claims.forEach((k, v) -> {
            map.put(k, v.asString());
        });

        return map;
    }

    public static String getUserId(String token) {
        Map<String, Object> map = JwtUtil.verityToken(token);
        String userId = (String) map.get("userId");
        if(StrUtil.isEmpty(userId)) {
            throw new BusinessException("token异常，为查询到uid");
        }

        return userId;
    }
}
